
package com.kaciula.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class WebService {

    private String mServiceUrl;

    private DefaultHttpClient mHttpClient;

    /* constants */
    private static final int CONNECTION_TIMEOUT = 100000;

    private static final int SOCKET_TIMEOUT = 100000;

    private static final String ENCODING_UTF_8 = "UTF-8";

    private static final String TAG = "WebService";

    public WebService(String webServiceBaseName) {
        this.mServiceUrl = webServiceBaseName;

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

        this.mHttpClient = new DefaultHttpClient(params);
    }

    public String get(String method, Map<String, String> params) {
        String url = null;
        HttpGet httpGet = null;
        HttpResponse response = null;
        String entity = null;

        try {
            url = mServiceUrl + URLEncoder.encode(method, ENCODING_UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e.getMessage());
        }

        int i = 0;
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (i == 0) {
                url += "?";
            } else {
                url += "&";
            }

            try {
                url += param.getKey() + "=" + URLEncoder.encode(param.getValue(), ENCODING_UTF_8);
            } catch (UnsupportedEncodingException e) {
                throw new AssertionError(e.getMessage());
            }

            i++;
        }

        httpGet = new HttpGet(url);
        Log.d(TAG, "URL=[" + url + "]");

        try {
            response = mHttpClient.execute(httpGet);
        } catch (Exception e) {
            throw new AssertionError(e.getMessage());
        }

        try {
            entity = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            throw new AssertionError(e.getMessage());
        }

        return entity;
    }

    public String post(String method, Object data, String reqContentType, String acceptContentType,
            String auth) {
        String url = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity dataEntity = null;
        String entity = null;

        try {
            url = mServiceUrl + URLEncoder.encode(method, ENCODING_UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e.getMessage());
        }

        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

        httpPost = new HttpPost(url);

        if (reqContentType != null) {
            httpPost.setHeader("Content-Type", reqContentType);
        } else {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }

        if (acceptContentType != null) {
            httpPost.setHeader("Accept", acceptContentType);
        }

        if (auth != null) {
            httpPost.setHeader("Authorization", "Basic " + auth);
        }

        try {
            if (data instanceof String) {
                dataEntity = new StringEntity((String) data, ENCODING_UTF_8);
            } else {
                if (data instanceof ByteArrayOutputStream) {
                    dataEntity = new ByteArrayEntity(((ByteArrayOutputStream) data).toByteArray());
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e.getMessage());
        }

        httpPost.setEntity(dataEntity);

        try {
            response = mHttpClient.execute(httpPost);

            Log.d(TAG, "status code=" + response.getStatusLine().getStatusCode());
            if (response != null) {
                entity = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            throw new AssertionError(e.getMessage());
        }

        return entity;
    }

}
